Exceptions and Exception Handling
Sources
Weiss, Section 2.5
Summary
Exceptions are a formal method used to respond to situations in Java where something unexpected happens
(usually, but not always an error). The basic vocabulary reflects the unusual situation:
One segment of code will try to execute;
if an unusual situation occurs, the code will throw an object called an exception.
The calling method can either catch the exception and handle it,
or propagate the exception using the keyword throws in the method header.
Finally, some code executes regardless of whether or not the exception was thrown.
This entire block of code is called a try-catch block.
There are many types of Exceptions (a whole hierarchy):
- Checked exceptions, like
FileNotFoundException
, produce a syntax error if you don't write code to catch them.
- Run-time exceptions, like array bounds access, don't; if they aren't caught, they halt the execution of the program.
- Errors, like OutOfMemoryError, are thrown by the Java Virtual Machine. They shouldn't be caught.
Hints:
If you want to throw an exception, you need to create one: throw new Exception("Help!!!");
Example: